package com.hj.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局的异常处理类
 *
 * @author 37460
 */

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    /**
     * SQLIntegrityConstraintViolationException异常处理方法
     *
     * @return  advice、pointCut
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {
        String message = exception.getMessage();
        //打印捕获的异常信息
        log.info(message);
        //是否包含异常信息关键字
        if (message.contains("Duplicate entry")) {
            String[] s = message.split(" ");
            return R.error(s[2]+"已存在");
        }
        //返回异常信息
        return R.error(message);
    }

    /**
     * BusinessException  业务异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public R<String> exceptionHandler(BusinessException ex) {
        //打印捕获的异常信息
        log.error(ex.getMessage());
        //返回异常信息
        return R.error(ex.getMessage());
    }
}
